package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
)

// nginxConfigHandler 处理 Nginx 配置管理页面
func nginxConfigHandler(w http.ResponseWriter, r *http.Request) {
	// 获取 Nginx 配置路径
	nginxConfPath, err := GetNginxConfPath("config.json")
	if err != nil {
		log.Printf("Failed to get nginx config path: %v\n", err)
		http.Error(w, fmt.Sprintf("Failed to get nginx config path: %v", err), http.StatusInternalServerError)
		return
	}

	// 获取当前目录（从查询参数）
	currentDir := r.URL.Query().Get("dir")
	if currentDir == "" {
		currentDir = nginxConfPath
	}

	// 列出目录内容
	files, err := ListNginxConfFiles(currentDir)
	if err != nil {
		log.Printf("Failed to list files: %v\n", err)
		http.Error(w, fmt.Sprintf("Failed to list files: %v", err), http.StatusInternalServerError)
		return
	}

	// 渲染模板
	tmpl := `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>Nginx 配置管理</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-light: #60a5fa;
            --primary-dark: #1e40af;
            --secondary-color: #06b6d4;
            --secondary-dark: #0891b2;
            --success-color: #10b981;
            --success-dark: #059669;
            --warning-color: #f59e0b;
            --warning-dark: #d97706;
            --danger-color: #ef4444;
            --danger-dark: #dc2626;
            --info-color: #0ea5e9;
            --info-dark: #0284c7;
            --light-color: #f8fafc;
            --light-secondary: #f1f5f9;
            --dark-color: #1e293b;
            --dark-light: #334155;
            --gray-color: #64748b;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --border-color: #e2e8f0;
            --card-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);
            --card-shadow-hover: 0 8px 16px rgba(15, 23, 42, 0.12);
            --input-border-focus: 0 0 0 3px rgba(59, 130, 246, 0.1);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            color: var(--dark-color);
            line-height: 1.6;
            font-size: 14px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--info-color) 100%);
            color: white;
            padding: 24px 0;
            box-shadow: var(--card-shadow);
            margin-bottom: 32px;
            border-radius: 0;
            backdrop-filter: blur(10px);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .logo i {
            font-size: 2rem;
            animation: slideIn 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .logo h1 {
            font-size: 1.8rem;
            font-weight: 600;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 16px;
            border-radius: 8px;
            text-decoration: none;
            transition: var(--transition);
            font-weight: 500;
            font-size: 0.95rem;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateX(-2px);
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 28px;
            box-shadow: var(--card-shadow);
            margin-bottom: 24px;
            border: 1px solid var(--border-color);
        }
        
        .breadcrumb {
            background: var(--gray-100);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            word-break: break-all;
            border: 1px solid var(--border-color);
            font-size: 0.9rem;
        }
        
        .breadcrumb i {
            color: var(--primary-color);
            margin-right: 8px;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.95rem;
            font-weight: 500;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
        }
        
        .btn-success {
            background: linear-gradient(135deg, var(--success-color), var(--success-dark));
            color: white;
        }
        
        .btn-warning {
            background: linear-gradient(135deg, var(--warning-color), var(--warning-dark));
            color: white;
        }
        
        .btn-danger {
            background: linear-gradient(135deg, var(--danger-color), var(--danger-dark));
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 14px 12px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.9rem;
        }
        
        th {
            background-color: var(--gray-100);
            font-weight: 600;
            color: var(--dark-color);
        }
        
        tr:hover {
            background-color: var(--light-secondary);
        }
        
        .file-icon {
            font-size: 1.2rem;
            margin-right: 8px;
        }
        
        .dir-icon {
            color: #ffc107;
        }
        
        .file-icon-default {
            color: #6c757d;
        }
        
        .action-links {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }
        
        .action-link {
            color: var(--primary-color);
            text-decoration: none;
            cursor: pointer;
            font-weight: 500;
            font-size: 0.9rem;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }
        
        .action-link:hover {
            color: var(--primary-dark);
            transform: translateY(-1px);
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 24px;
            border: none;
            border-radius: 12px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 20px 40px rgba(15, 23, 42, 0.15);
        }
        
        .close {
            color: var(--gray-color);
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: var(--transition);
            padding: 0 8px;
        }
        
        .close:hover,
        .close:focus {
            color: var(--dark-color);
            transform: rotate(90deg);
        }
        
        textarea {
            width: 100%;
            min-height: 400px;
            padding: 14px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-family: 'Courier New', 'Monaco', monospace;
            font-size: 0.9rem;
            resize: vertical;
            transition: var(--transition);
        }
        
        textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: var(--input-border-focus);
        }
        
        input[type="text"] {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 0.95rem;
            transition: var(--transition);
        }
        
        input[type="text"]:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: var(--input-border-focus);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark-color);
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 16px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            font-size: 0.95rem;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
            transform: translateX(400px);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1001;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.success {
            background: linear-gradient(135deg, var(--success-color), var(--success-dark));
        }
        
        .notification.error {
            background: linear-gradient(135deg, var(--danger-color), var(--danger-dark));
        }
        
        /* 自定义确认弹窗样式 */
        .custom-confirm-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .custom-confirm-box {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(15, 23, 42, 0.15);
            padding: 32px;
            min-width: 400px;
            max-width: 500px;
            animation: slideDown 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 10001;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translate(-50%, -60%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }
        
        .confirm-icon {
            font-size: 3rem;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .confirm-icon.warning {
            color: #ff9800;
        }
        
        .confirm-icon.danger {
            color: #f44336;
        }
        
        .confirm-title {
            font-size: 1.5rem;
            font-weight: 600;
            text-align: center;
            margin-bottom: 15px;
            color: var(--dark-color);
        }
        
        .confirm-message {
            text-align: center;
            color: var(--gray-color);
            margin-bottom: 25px;
            line-height: 1.6;
            white-space: pre-wrap;
        }
        
        .confirm-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }
        
        .confirm-btn {
            padding: 12px 30px;
            border: none;
            border-radius: 25px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            min-width: 100px;
        }
        
        .confirm-btn-yes {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
        }
        
        .confirm-btn-yes:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
        }
        
        .confirm-btn-no {
            background: #e0e0e0;
            color: #666;
        }
        
        .confirm-btn-no:hover {
            background: #d0d0d0;
            transform: translateY(-2px);
        }
        
        .nginx-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <header>
        <div class="header-content">
            <div class="logo">
                <i class="fas fa-cog"></i>
                <h1>Nginx 配置文件管理</h1>
            </div>
            <a href="/" class="back-btn">
                <i class="fas fa-arrow-left"></i> 返回主页
            </a>
        </div>
    </header>
    
    <div class="container">
        <div class="card">
            <div class="breadcrumb">
                <i class="fas fa-folder-open"></i>
                <strong>当前目录：</strong> {{.CurrentDir}}
            </div>
            
            <div class="action-buttons">
                {{if ne .CurrentDir .RootDir}}
                <a href="/nginxConfig?dir={{.ParentDir}}" class="btn btn-primary">
                    <i class="fas fa-level-up-alt"></i> 上级目录
                </a>
                {{end}}
                <button onclick="showCreateFileModal()" class="btn btn-success">
                    <i class="fas fa-file-plus"></i> 新建文件
                </button>
                <button onclick="showCreateDirModal()" class="btn btn-success">
                    <i class="fas fa-folder-plus"></i> 新建目录
                </button>
            </div>
            
            <table>
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>类型</th>
                        <th>大小</th>
                        <th>修改时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {{range .Files}}
                    <tr>
                        <td>
                            {{if .IsDir}}
                            <i class="fas fa-folder file-icon dir-icon"></i>
                            <a href="/nginxConfig?dir={{.Path}}">{{.Name}}</a>
                            {{else}}
                            <i class="fas fa-file file-icon file-icon-default"></i>
                            {{.Name}}
                            {{end}}
                        </td>
                        <td>{{if .IsDir}}目录{{else}}文件{{end}}</td>
                        <td>{{if .IsDir}}-{{else}}{{.Size}} B{{end}}</td>
                        <td>{{.ModTime.Format "2006-01-02 15:04:05"}}</td>
                        <td class="action-links">
                            {{if not .IsDir}}
                            <a class="action-link" onclick="viewFile('{{.Path}}', '{{.Name}}')">
                                <i class="fas fa-eye"></i> 查看
                            </a>
                            <a class="action-link" onclick="editFile('{{.Path}}', '{{.Name}}')">
                                <i class="fas fa-edit"></i> 编辑
                            </a>
                            {{end}}
                            <a class="action-link" onclick="renameItem('{{.Path}}', '{{.Name}}', {{.IsDir}})">
                                <i class="fas fa-pen"></i> 重命名
                            </a>
                            <a class="action-link" style="color: var(--danger-color);" onclick="deleteItem('{{.Path}}', '{{.Name}}', {{.IsDir}})">
                                <i class="fas fa-trash"></i> 删除
                            </a>
                        </td>
                    </tr>
                    {{end}}
                </tbody>
            </table>
        </div>
        
        <div class="card">
            <h3><i class="fas fa-tools"></i> Nginx 操作</h3>
            <div class="nginx-actions">
                <button onclick="testNginxConfig()" class="btn btn-primary">
                    <i class="fas fa-check-circle"></i> 测试配置
                </button>
                <button onclick="reloadNginx()" class="btn btn-warning">
                    <i class="fas fa-sync"></i> 重载配置
                </button>
                <button onclick="restartNginx()" class="btn btn-danger">
                    <i class="fas fa-power-off"></i> 重启 Nginx
                </button>
            </div>
        </div>
    </div>
    
    <!-- 查看文件模态框 -->
    <div id="viewFileModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('viewFileModal')">&times;</span>
            <h2><i class="fas fa-file-alt"></i> 查看文件: <span id="viewFileName"></span></h2>
            <textarea id="viewFileContent" readonly></textarea>
        </div>
    </div>
    
    <!-- 编辑文件模态框 -->
    <div id="editFileModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('editFileModal')">&times;</span>
            <h2><i class="fas fa-edit"></i> 编辑文件: <span id="editFileName"></span></h2>
            <textarea id="editFileContent"></textarea>
            <input type="hidden" id="editFilePath">
            <div style="margin-top: 15px;">
                <button onclick="saveFile()" class="btn btn-success">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button onclick="closeModal('editFileModal')" class="btn btn-danger">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>
    
    <!-- 新建文件模态框 -->
    <div id="createFileModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('createFileModal')">&times;</span>
            <h2><i class="fas fa-file-plus"></i> 新建文件</h2>
            <div class="form-group">
                <label>文件名:</label>
                <input type="text" id="newFileName" placeholder="输入文件名">
            </div>
            <div class="form-group">
                <label>文件内容:</label>
                <textarea id="newFileContent"></textarea>
            </div>
            <div>
                <button onclick="createFile()" class="btn btn-success">
                    <i class="fas fa-check"></i> 创建
                </button>
                <button onclick="closeModal('createFileModal')" class="btn btn-danger">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>
    
    <!-- 新建目录模态框 -->
    <div id="createDirModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('createDirModal')">&times;</span>
            <h2><i class="fas fa-folder-plus"></i> 新建目录</h2>
            <div class="form-group">
                <label>目录名:</label>
                <input type="text" id="newDirName" placeholder="输入目录名">
            </div>
            <div>
                <button onclick="createDir()" class="btn btn-success">
                    <i class="fas fa-check"></i> 创建
                </button>
                <button onclick="closeModal('createDirModal')" class="btn btn-danger">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>
    
    <div id="notification" class="notification"></div>
    
    <!-- 自定义确认弹窗 -->
    <div id="customConfirmOverlay" class="custom-confirm-overlay">
        <div class="custom-confirm-box">
            <div id="confirmIcon" class="confirm-icon"></div>
            <div id="confirmTitle" class="confirm-title"></div>
            <div id="confirmMessage" class="confirm-message"></div>
            <div class="confirm-buttons">
                <button id="confirmYes" class="confirm-btn confirm-btn-yes">确定</button>
                <button id="confirmNo" class="confirm-btn confirm-btn-no">取消</button>
            </div>
        </div>
    </div>
    
    <script>
        const currentDir = '{{.CurrentDir}}';
        
        function showNotification(message, isSuccess) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification ' + (isSuccess ? 'success' : 'error');
            notification.classList.add('show');
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
        
        // 自定义确认弹窗
        function showCustomConfirm(title, message, iconType, onConfirm) {
            const overlay = document.getElementById('customConfirmOverlay');
            const icon = document.getElementById('confirmIcon');
            const titleEl = document.getElementById('confirmTitle');
            const messageEl = document.getElementById('confirmMessage');
            const yesBtn = document.getElementById('confirmYes');
            const noBtn = document.getElementById('confirmNo');
            
            // 设置内容
            titleEl.textContent = title;
            messageEl.textContent = message;
            
            // 设置图标
            if (iconType === 'warning') {
                icon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
                icon.className = 'confirm-icon warning';
            } else if (iconType === 'danger') {
                icon.innerHTML = '<i class="fas fa-exclamation-circle"></i>';
                icon.className = 'confirm-icon danger';
            }
            
            // 显示弹窗
            overlay.style.display = 'block';
            
            // 处理确认
            yesBtn.onclick = function() {
                overlay.style.display = 'none';
                if (onConfirm) onConfirm();
            };
            
            // 处理取消
            noBtn.onclick = function() {
                overlay.style.display = 'none';
            };
            
            // 点击背景关闭
            overlay.onclick = function(e) {
                if (e.target === overlay) {
                    overlay.style.display = 'none';
                }
            };
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function viewFile(filePath, fileName) {
            fetch('/nginxConfig/read?path=' + encodeURIComponent(filePath))
                .then(response => response.text())
                .then(data => {
                    document.getElementById('viewFileName').textContent = fileName;
                    document.getElementById('viewFileContent').value = data;
                    document.getElementById('viewFileModal').style.display = 'block';
                })
                .catch(error => {
                    showNotification('读取文件失败: ' + error, false);
                });
        }
        
        function editFile(filePath, fileName) {
            fetch('/nginxConfig/read?path=' + encodeURIComponent(filePath))
                .then(response => response.text())
                .then(data => {
                    document.getElementById('editFileName').textContent = fileName;
                    document.getElementById('editFileContent').value = data;
                    document.getElementById('editFilePath').value = filePath;
                    document.getElementById('editFileModal').style.display = 'block';
                })
                .catch(error => {
                    showNotification('读取文件失败: ' + error, false);
                });
        }
        
        function saveFile() {
            const filePath = document.getElementById('editFilePath').value;
            const content = document.getElementById('editFileContent').value;
            
            fetch('/nginxConfig/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'path=' + encodeURIComponent(filePath) + '&content=' + encodeURIComponent(content)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('文件保存成功', true);
                    closeModal('editFileModal');
                } else {
                    showNotification('文件保存失败: ' + data.error, false);
                }
            })
            .catch(error => {
                showNotification('文件保存失败: ' + error, false);
            });
        }
        
        function showCreateFileModal() {
            document.getElementById('newFileName').value = '';
            document.getElementById('newFileContent').value = '';
            document.getElementById('createFileModal').style.display = 'block';
        }
        
        function showCreateDirModal() {
            document.getElementById('newDirName').value = '';
            document.getElementById('createDirModal').style.display = 'block';
        }
        
        function createFile() {
            const fileName = document.getElementById('newFileName').value.trim();
            const content = document.getElementById('newFileContent').value;
            
            if (!fileName) {
                showNotification('请输入文件名', false);
                return;
            }
            
            const filePath = currentDir + '/' + fileName;
            
            fetch('/nginxConfig/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'path=' + encodeURIComponent(filePath) + '&content=' + encodeURIComponent(content)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('文件创建成功', true);
                    closeModal('createFileModal');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showNotification('文件创建失败: ' + data.error, false);
                }
            })
            .catch(error => {
                showNotification('文件创建失败: ' + error, false);
            });
        }
        
        function createDir() {
            const dirName = document.getElementById('newDirName').value.trim();
            
            if (!dirName) {
                showNotification('请输入目录名', false);
                return;
            }
            
            const dirPath = currentDir + '/' + dirName;
            
            fetch('/nginxConfig/createDir', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'path=' + encodeURIComponent(dirPath)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('目录创建成功', true);
                    closeModal('createDirModal');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showNotification('目录创建失败: ' + data.error, false);
                }
            })
            .catch(error => {
                showNotification('目录创建失败: ' + error, false);
            });
        }
        
        function deleteItem(path, name, isDir) {
            const itemType = isDir ? '目录' : '文件';
            if (!confirm('确定要删除' + itemType + ' "' + name + '" 吗？')) {
                return;
            }
            
            const endpoint = isDir ? '/nginxConfig/deleteDir' : '/nginxConfig/delete';
            
            fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'path=' + encodeURIComponent(path)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(itemType + '删除成功', true);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showNotification(itemType + '删除失败: ' + data.error, false);
                }
            })
            .catch(error => {
                showNotification(itemType + '删除失败: ' + error, false);
            });
        }
        
        function renameItem(path, name, isDir) {
            const itemType = isDir ? '目录' : '文件';
            const newName = prompt('请输入新的' + itemType + '名称:', name);
            
            if (!newName || newName === name) {
                return;
            }
            
            const parentDir = path.substring(0, path.lastIndexOf('/'));
            const newPath = parentDir + '/' + newName;
            
            fetch('/nginxConfig/rename', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'oldPath=' + encodeURIComponent(path) + '&newPath=' + encodeURIComponent(newPath)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(itemType + '重命名成功', true);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showNotification(itemType + '重命名失败: ' + data.error, false);
                }
            })
            .catch(error => {
                showNotification(itemType + '重命名失败: ' + error, false);
            });
        }
        
        function testNginxConfig() {
            fetch('/nginxConfig/test', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('Nginx 配置测试通过', true);
                } else {
                    // 显示详细的错误信息
                    showCustomConfirm(
                        'Nginx 配置测试失败',
                        data.error || 'Nginx 配置测试失败',
                        'danger',
                        null  // 不需要确认按钮的回调
                    );
                }
            })
            .catch(error => {
                showNotification('测试失败: ' + error, false);
            });
        }
        
        function reloadNginx() {
            showCustomConfirm(
                '重载 Nginx 配置',
                '确定要重载 Nginx 配置吗？系统将先测试配置，然后重载服务。',
                'warning',
                function() {
                    // 先测试配置
                    fetch('/nginxConfig/test', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 配置测试通过，执行重载
                            return fetch('/reloadNginx', {
                                method: 'POST'
                            });
                        } else {
                            // 配置测试失败
                            throw new Error('配置测试失败: ' + data.error);
                        }
                    })
                    .then(response => {
                        if (response.ok) {
                            showNotification('Nginx 重载成功', true);
                        } else {
                            return response.text().then(text => {
                                throw new Error(text || 'Nginx 重载失败');
                            });
                        }
                    })
                    .catch(error => {
                        showNotification('Nginx 重载失败: ' + error.message, false);
                    });
                }
            );
        }
        
        function restartNginx() {
            showCustomConfirm(
                '重启 Nginx 服务',
                '确定要重启 Nginx 服务吗？系统将先测试配置，然后重启服务。',
                'danger',
                function() {
                    // 先测试配置
                    fetch('/nginxConfig/test', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 配置测试通过，执行重启
                            return fetch('/restartNginx', {
                                method: 'POST'
                            });
                        } else {
                            // 配置测试失败
                            throw new Error('配置测试失败: ' + data.error);
                        }
                    })
                    .then(response => {
                        if (response.ok) {
                            showNotification('Nginx 重启成功', true);
                        } else {
                            return response.text().then(text => {
                                throw new Error(text || 'Nginx 重启失败');
                            });
                        }
                    })
                    .catch(error => {
                        showNotification('Nginx 重启失败: ' + error.message, false);
                    });
                }
            );
        }
    </script>
</body>
</html>`

	t, err := template.New("nginxConfig").Parse(tmpl)
	if err != nil {
		log.Printf("Failed to parse template: %v\n", err)
		http.Error(w, fmt.Sprintf("Failed to parse template: %v", err), http.StatusInternalServerError)
		return
	}

	// 计算父目录
	parentDir := filepath.Dir(currentDir)
	if parentDir == currentDir {
		parentDir = ""
	}

	data := struct {
		CurrentDir string
		RootDir    string
		ParentDir  string
		Files      []FileInfo
	}{
		CurrentDir: currentDir,
		RootDir:    nginxConfPath,
		ParentDir:  parentDir,
		Files:      files,
	}

	err = t.Execute(w, data)
	if err != nil {
		log.Printf("Failed to execute template: %v\n", err)
		http.Error(w, fmt.Sprintf("Failed to execute template: %v", err), http.StatusInternalServerError)
		return
	}
}

// nginxConfigReadHandler 读取配置文件内容
func nginxConfigReadHandler(w http.ResponseWriter, r *http.Request) {
	filePath := r.URL.Query().Get("path")
	if filePath == "" {
		http.Error(w, "File path is required", http.StatusBadRequest)
		return
	}

	content, err := ReadNginxConfFile(filePath)
	if err != nil {
		log.Printf("Failed to read file: %v\n", err)
		http.Error(w, fmt.Sprintf("Failed to read file: %v", err), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	fmt.Fprint(w, content)
}

// nginxConfigUpdateHandler 更新配置文件
func nginxConfigUpdateHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	filePath := r.FormValue("path")
	content := r.FormValue("content")

	if filePath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "File path is required"}`)
		return
	}

	err := UpdateNginxConfFile(filePath, content)
	if err != nil {
		log.Printf("Failed to update file: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigCreateHandler 创建新文件
func nginxConfigCreateHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	filePath := r.FormValue("path")
	content := r.FormValue("content")

	if filePath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "File path is required"}`)
		return
	}

	err := CreateNginxConfFile(filePath, content)
	if err != nil {
		log.Printf("Failed to create file: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigCreateDirHandler 创建新目录
func nginxConfigCreateDirHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	dirPath := r.FormValue("path")

	if dirPath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "Directory path is required"}`)
		return
	}

	err := CreateNginxConfDir(dirPath)
	if err != nil {
		log.Printf("Failed to create directory: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigDeleteHandler 删除文件
func nginxConfigDeleteHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	filePath := r.FormValue("path")

	if filePath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "File path is required"}`)
		return
	}

	err := DeleteNginxConfFile(filePath)
	if err != nil {
		log.Printf("Failed to delete file: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigDeleteDirHandler 删除目录
func nginxConfigDeleteDirHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	dirPath := r.FormValue("path")

	if dirPath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "Directory path is required"}`)
		return
	}

	err := DeleteNginxConfDir(dirPath)
	if err != nil {
		log.Printf("Failed to delete directory: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigRenameHandler 重命名文件或目录
func nginxConfigRenameHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	oldPath := r.FormValue("oldPath")
	newPath := r.FormValue("newPath")

	if oldPath == "" || newPath == "" {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "Both old and new paths are required"}`)
		return
	}

	err := RenameNginxConfFileOrDir(oldPath, newPath)
	if err != nil {
		log.Printf("Failed to rename: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"success": false, "error": "%s"}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// nginxConfigTestHandler 测试 Nginx 配置
func nginxConfigTestHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	err := TestNginxConfig()
	if err != nil {
		log.Printf("Nginx config test failed: %v\n", err)
		w.Header().Set("Content-Type", "application/json")
		// 返回详细的错误信息
		fmt.Fprintf(w, `{"success": false, "error": %q}`, err.Error())
		return
	}

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"success": true}`)
}

// reloadNginxHandler 重载 Nginx 配置
func reloadNginxHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	err := ReloadNginx()
	if err != nil {
		log.Printf("Failed to reload nginx: %v\n", err)
		// 返回错误响应
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		fmt.Fprintf(w, `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>重载失败</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            padding: 40px;
            max-width: 600px;
            text-align: center;
            animation: slideIn 0.5s ease-out;
        }
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .icon {
            font-size: 4rem;
            color: #f72585;
            margin-bottom: 20px;
            animation: shake 0.5s;
        }
        @keyframes shake {
            0%%, 100%% { transform: translateX(0); }
            25%% { transform: translateX(-10px); }
            75%% { transform: translateX(10px); }
        }
        h1 {
            color: #f72585;
            font-size: 2rem;
            margin-bottom: 15px;
        }
        .message {
            color: #6c757d;
            font-size: 1.1rem;
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .error-detail {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            color: #856404;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            text-align: left;
            word-break: break-all;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            text-decoration: none;
            border-radius: 25px;
            font-weight: 500;
            margin-top: 20px;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
            font-size: 1rem;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="icon">
            <i class="fas fa-exclamation-triangle"></i>
        </div>
        <h1>Nginx 重载失败</h1>
        <p class="message">重载 Nginx 配置时发生错误</p>
        <div class="error-detail">
            <strong>错误信息：</strong><br>%s
        </div>
        <p class="message">请检查 Nginx 配置文件是否正确，然后重试。</p>
        <a href="/" class="btn">
            <i class="fas fa-home"></i> 返回主页
        </a>
    </div>
</body>
</html>
`, err.Error())
		return
	}

	// 返回成功响应
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>重载成功</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            padding: 40px;
            max-width: 600px;
            text-align: center;
            animation: slideIn 0.5s ease-out;
        }
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .icon {
            font-size: 4rem;
            color: #4CAF50;
            margin-bottom: 20px;
            animation: bounce 1s;
        }
        @keyframes bounce {
            0%%, 20%%, 50%%, 80%%, 100%% { transform: translateY(0); }
            40%% { transform: translateY(-20px); }
            60%% { transform: translateY(-10px); }
        }
        h1 {
            color: #4CAF50;
            font-size: 2rem;
            margin-bottom: 15px;
        }
        .message {
            color: #6c757d;
            font-size: 1.1rem;
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .info-box {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            color: #0c5460;
        }
        .btn-group {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
            flex-wrap: wrap;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 30px;
            color: white;
            text-decoration: none;
            border-radius: 25px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
            font-size: 1rem;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .btn-secondary {
            background: linear-gradient(135deg, #4CAF50, #2E7D32);
        }
        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <h1>Nginx 重载成功！</h1>
        <p class="message">Nginx 配置已成功重载，新配置已生效。</p>
        <div class="info-box">
            <i class="fas fa-info-circle"></i> Nginx 已重新加载配置文件，无需重启服务。
        </div>
        <div class="btn-group">
            <a href="/" class="btn btn-primary">
                <i class="fas fa-home"></i> 返回主页
            </a>
            <a href="/nginxConfig" class="btn btn-secondary">
                <i class="fas fa-cog"></i> 配置管理
            </a>
        </div>
    </div>
</body>
</html>
`)
}
